﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ElectronicCommerce.Framework.Payment.Utility
{
    public static class PropertyExtensions
    {
        /// <summary>
        /// 支付平台服务入口参数平移转换
        /// </summary>
        /// <param name="tradeInfo"></param>
        /// <returns></returns>
        public static NameValueCollection PublicPropertyKeyValues(this object obj)
        {
            NameValueCollection keyValues = new NameValueCollection();

            PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo propertyInfo in properties)
            {
                keyValues.Add(propertyInfo.Name, propertyInfo.GetValue(obj, null) as string);
            }

            return keyValues;
        }

        /// <summary>
        /// 支付平台服务入口参数平移转换
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static List<RequestParam> PublicPropertyNameValues(this object obj)
        {
            List<RequestParam> keyValues = new List<RequestParam>();
            PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo propertyInfo in properties)
            {
                keyValues.Add(new RequestParam(propertyInfo.Name, propertyInfo.GetValue(obj, null) as string));
            }

            return keyValues;
        }

        /// <summary>
        /// 把公共属性Key=Value化为字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string PublicPropertyNameValueString(this object obj)
        {
            List<RequestParam> rps = obj.PublicPropertyNameValues();
            StringBuilder sb = new StringBuilder();
            foreach (RequestParam rp in rps)
            {
                sb.AppendFormat("{0}={1}{2}", rp.Key, rp.Value, Environment.NewLine);
            }
            return sb.ToString();
        }
    }
}
